package com.bage.finance.biz.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.bage.common.exception.BizException;
import com.bage.common.exception.ParameterException;
import com.bage.common.service.TokenService;
import com.bage.common.util.DateUtil;
import com.bage.common.util.MyUtil;
import com.bage.finance.biz.config.ObjectConvertor;
import com.bage.finance.biz.constant.RedisKeyConstant;
import com.bage.finance.biz.domain.Member;
import com.bage.finance.biz.domain.MemberBindPhone;
import com.bage.finance.biz.dto.form.GetUserSmsCodeForm;
import com.bage.finance.biz.dto.form.SmsCodeResult;
import com.bage.finance.biz.dto.form.UpdatePhoneForm;
import com.bage.finance.biz.dto.vo.CurrentInfoVo;
import com.bage.finance.biz.mapper.MemberBindPhoneMapper;
import com.bage.finance.biz.service.MemberComService;
import com.bage.finance.biz.service.MemberService;
import com.bage.finance.biz.service.SmsService;
import com.bage.mybatis.help.MyBatisWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.bage.finance.biz.domain.MemberBindPhoneField.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class MemberComServiceImpl implements MemberComService {

    final MemberService memberService;

    final TokenService<Member> tokenService;

    final ObjectConvertor objectConvertor;

    final RedisTemplate<String, Object> redisTemplate;

    final SmsService smsService;

    final MemberBindPhoneMapper memberBindPhoneMapper;

    @Override
    public CurrentInfoVo getCurrentInfo() {
        Member member = memberService.get(tokenService.getThreadLocalUserId());
        if (Objects.isNull(member)) {
            throw new BizException("用户不存在");
        }
        if (member.getDisable()) {
            throw new BizException("用户被禁用");
        }
        return objectConvertor.toCurrentInfoVo(member);
    }

    @Override
    public String getBase64Code() {
        LineCaptcha shearCaptcha = CaptchaUtil.createLineCaptcha(300, 192, 5, 1000);
        String code = shearCaptcha.getCode();
        log.info("客户端member_id: {}, 图形验证码: {}", tokenService.getThreadLocalUserId(), code);
        redisTemplate.opsForValue().set(RedisKeyConstant.USER_GRAPHIC_VERIFICATION_CODE + tokenService.getThreadLocalUserId(), code, 15, TimeUnit.MINUTES);
        return shearCaptcha.getImageBase64();
    }

    @Override
    public void sendSmsCode(GetUserSmsCodeForm form) {
        // 校验图形验证码
        checkBase64Code(form.getCode());
        String key = RedisKeyConstant.SMS_CODE + form.getSmsCodeType() + tokenService.getThreadLocalUserId();
        SmsCodeResult smsCodeResult = (SmsCodeResult) redisTemplate.opsForValue().get(key);
        if (smsCodeResult != null) {
            Duration duration = DateUtil.getDuration(smsCodeResult.getGetTime(), DateUtil.getSystemTime());
            if (duration.getSeconds() < 60) {
                throw new BizException("验证码获取太频繁, 请稍后重试");
            }
        }
        int smsCode = MyUtil.getRandom(6);
        smsCodeResult = new SmsCodeResult();
        smsCodeResult.setCode(String.valueOf(smsCode));
        smsCodeResult.setGetTime(DateUtil.getSystemTime());
        smsCodeResult.setPhone(form.getPhone());
        redisTemplate.opsForValue().set(key, smsCodeResult, 15, TimeUnit.MINUTES);
        log.info("用户id: {}, 手机: {}, 短信验证码: {}", tokenService.getThreadLocalUserId(), form.getPhone(), smsCode);
        smsService.sendSmsCode(form.getPhone(), smsCodeResult.getCode(), form.getSmsCodeType());
    }

    @Override
    public Boolean updatePhone(UpdatePhoneForm form) {
        MyBatisWrapper<MemberBindPhone> wrapper = new MyBatisWrapper<>();
        wrapper.update(setPhone(form.getPhone()))
                .whereBuilder()
                .andEq(setMemberId(tokenService.getThreadLocalUserId()))
                .andEq(setDisable(false));
        return memberBindPhoneMapper.updateField(wrapper) > 0;
    }

    /**
     * 校验图形验证码
     * @param code
     * @return
     */
    private boolean checkBase64Code(String code) {
        // 生成图片,获取base64编码字符串
        String cacheCode = (String) redisTemplate.opsForValue().get(RedisKeyConstant.USER_GRAPHIC_VERIFICATION_CODE + tokenService.getThreadLocalUserId());
        redisTemplate.delete(RedisKeyConstant.USER_GRAPHIC_VERIFICATION_CODE + tokenService.getThreadLocalUserId());
        if (!code.equalsIgnoreCase(cacheCode)) {
            throw new ParameterException("code", "图形验证码错误!");
        }
        return true;
    }
}
